package com.generic.mybatis.dal.dao.criteria;

import com.generic.mybatis.dal.interceptor.automap.TableMapper;
import org.apache.ibatis.jdbc.SQL;

import java.util.Map;

/**
 * and SQL文组装
 *
 * @author wuaj
 */
public class AndCriteria implements Criteria {

    private final Criteria[] criterias;

    public AndCriteria(Criteria... criterias) {
        this.criterias = criterias;
    }

    @Override
    public void toSql(TableMapper mapper, SQL sql, Map paramMap) {
        SQL newSql = new SQL();
        newSql.SELECT("");
        if (criterias.length > 0) {
            criterias[0].toSql(mapper, newSql, paramMap);
        }
        if (criterias.length > 1) {
            newSql.AND();
            for (int i = 1; i < criterias.length; i++) {
                criterias[i].toSql(mapper, newSql, paramMap);
                if (i + 1 < criterias.length) {
                    newSql.AND();
                }
            }
        }

        String where = newSql.toString();
        sql.WHERE(where.substring(where.indexOf("WHERE") + 5));
    }
}
